import { generateUniqueId } from "utils/utils";
import { ActionBase, ActionBaseOfCreep } from "../ActionBase";
import { priority } from "utils/constants/definetypes";
import { LabTaskHelper } from "utils/task/LabTaskHelper";

 
/**
 *  填充lab
 */
export class ActionLabReaction  extends ActionBase<IActionCMD<"react">>
{
    public execute(action: IActionCMD<"react">): ActionCode 
    {
        
        const room = action.arg.entity as Required<Room>;
        if(!room)
        {
            return 0;
        }
        
        const labentity = room.getEntity("LabEntity");
        const baselabs = labentity.BaseLabs();
        const top = action.arg.task;
        const currentReactant = LabTaskHelper.GetReactant(action.arg.task.data.arg);
        if(!currentReactant)
        {
            return -2
        }
    
        if(baselabs.length == 2  )
        {
            let result=1;
            for(const lab of labentity.ReactionLabs())
            {
                result = this.RunReaction(currentReactant,baselabs[0],baselabs[1],lab);
                if(result == ERR_NOT_ENOUGH_RESOURCES)
                {
                    break;
                }
            }
            if(result!= ERR_NOT_ENOUGH_RESOURCES)
            {
                top.ttl = top.ttl + 1000; // 刷新过期时间
            }
        }
        return 0;
    }
    private RunReaction(currentReactant:LabReaction,base1:StructureLab,base2:StructureLab,reaction:StructureLab):ScreepsReturnCode|1
    {
        // const currentReactant = LabTaskHelper.GetReactant(task);
     
        if(reaction.cooldown !=0)
        {
            return ERR_BUSY;
        }
        
        if(currentReactant && currentReactant.Reactant.amount !==undefined)
        {
            const code = reaction.runReaction(base1,base2);
           
            if(code == OK  )
            {
                const eff = _.find(reaction.effects,e=>e.effect == PWR_OPERATE_LAB);
                let addcount = 0;
                if(eff && (eff as PowerEffect).level )
                {
                    if((eff as PowerEffect).ticksRemaining === 0)
                    {
                        //
                        // global.LogDebug(`OP lab的结束时间为0 但是level还能取到`);
                    }
                    if((eff as PowerEffect).ticksRemaining)
                    {
                        (eff as PowerEffect).ticksRemaining
                    addcount = (eff as PowerEffect).level *2;
                    }
                }
                currentReactant.Reactant.amount+=(5+addcount);
                
                // currentReactant.BaseA.number-=5;
                // currentReactant.BaseB.number-=5;
            }
            else
            {
                // 当lab 被op 之后。资源数量为5不足 会导致反应失败
                // global.LogDebug(` 反应失败 ${code} ${JSON.stringify(task)})`);
            }
            return code;
        }
        return ERR_BUSY;
    }
}